<template>
	<view class="content">
		<view class="container">
		  <!-- 添加设备 开始 -->
		  <view class="add-device">
		    <view class="add-box">
		      <image class="img-cover" src="./bloodGlucose.jpg" style="height:317.5rpx;"></image>
		      <picker @change="bindPickerChange" :value="typeIndex" :range="typeArr">
		        <view class="picker">
		          {{typeArr[typeIndex]}}
		          <image class="img-icon" src=""></image>
		        </view>
		      </picker>
		      <input class="input-box" placeholder="请输入序列号" :value="deviceInput" @input="deviceInput" maxlength="6"></input>
		      <view class="add-btn" @tap="add">读取设备</view>
		    </view> 
		  </view>
		  <!-- 添加设备 结束 -->
		</view>
	</view>

</template>

<script>
	import {oss_host} from '@/config/config.js';
	import Vue from 'vue'
	import {
		fail
	} from 'assert';
	import store from '@/store/index.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
	// 骨架屏
 
	import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import tuiTag from '@/components/tag/tag'
	import blood from '@/utils/dev/blood/blood.js'
	import F2 from '@/js_sdk/uni-f2/f2.min.js'
	// import utils from "../../../../utils/sannuo.js";
	import { DevComm } from '../../../../utils/microtech-devicecomm.min.js';
	const microtechDevComm = DevComm.init();
	var app = getApp();
	
	function wrapEvent(e) {
	  if (!e) return
	  if (!e.preventDefault) {
	    e.preventDefault = function() {}
	  }
	  return e
	}
	let chart = null
	const lineCharts = {},
		optionAs = {};
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			tuiSkeleton,
			tuiTag,
			// LineChart,
			uniPopup,
			uniPopupDialog
		},
		data() {
			return {
				echartsData:[],
				mBottom: '0px',
				OSS_HOST: oss_host,
				typeArr: ['血糖仪'], //设备数组（显示名）
				deviceTypeArr: [2], //2:bgmeter (服务器)
				typeIndex: 0, // 1:bgmeter (选择控件索引)
			
				prefix: [], //血糖仪允许的前缀列表
				deviceUuid: "", //service uuid
				deviceService: [],
				deviceInput: 'R0009O', //设备编号输入框
				btAvailable: false, //自定义蓝牙可用状态
				btTimer: 0, //蓝牙计时器，超时
			
				// 蓝牙id
				deviceId: '',
				serviceId: '',
				characteristicId: '',
			
				isLoaded: false,
				data: {
					article: [],
					userInfo: {
						bindStatus: false,
						deviceId: ''
					},
					check: {}
					
				},
				
				connStatus: -1, //蓝牙连接状态  0 未连接  1 连接中  2 已连接  8 中断连接  9 绑定用户失败  10 获取蓝牙服务失败
				//connType  reconnect  重连   create  创建蓝牙连接
				errorMsg: {
					7: {
						msg: '用户绑定设备失败',
						code: '设备已被其它用户绑定,请先解绑设备',
						connType: 'reconnect',
						src: ''
					},
					8: {
						msg: '搜索超时,检测未发现蓝牙设备...',
						code: '请确保蓝牙设备已开机,或处于连接状态',
						connType: 'create',
						src: ''
					},
					9: {
						msg: '用户绑定设备失败',
						code: '服务器繁忙,请重新连接设备',
						connType: 'create',
						src: ''
					},
					10: {
						msg: '连接蓝牙设备失败',
						code: '请打开设备,重新连接或重新获取蓝牙设备',
						connType: 'reconnect',
						src: ''
					},
					20: {
						msg: 'mol浓度值太低',
						code: 'mol浓度值太低',
						connType: 'reconnect',
						src: ''
					},
					21: {
						msg: 'mol浓度值太高',
						code: 'mol浓度值太高',
						connType: 'reconnect',
						src: ''
					},
					22: {
						msg: '测量上传失败',
						code: '测量上传失败',
						connType: 'reconnect',
						src: ''
					},
					23: {
						msg: '血液异常重新测量',
						code: '血液异常重新测量',
						connType: 'reconnect',
						src: ''
					},
					30: {
						msg: '开始测量',
						code: '请把试纸插入到机器中保持设备常亮然后使用采血笔进行采血',
						connType: 'reconnect',
						src: ''
					},
					31: {
						msg: '请往试纸滴血',
						code: '请往试纸滴血',
						connType: 'reconnect',
						src: ''
					},
					32: {
						msg: '血液已经滴下等待结果',
						code: '血液已经滴下等待结果',
						connType: 'reconnect',
						src: ''
					},
				},
				isCancel: false,
				changeDevstatus:false,//是否已选择设备 
				isGlu:false,
				isUa:false,
				isMyCuia:false,
				canvasImg:null,
				changeDevValue:0 ,//选择连接的设备值,
				device_uuid:'', //ios device_uuid
				bind_mycuid:0, //是否从设备管理跳过来绑定民康
				rebind:false,
				closeBlue:false //取消蓝牙连接
			};
		},
		created() {
	
		},
		onHide() {
			// this.closeBluetoothAdapter()
		},
		/**
		   * 生命周期函数--监听页面加载
		   */
		  onLoad: function (options) {
		    
			this.isLoaded = true
			this.prefix = microtechDevComm.devicePrefix
			this.deviceUuid = microtechDevComm.serviceUuid
			this.deviceService = microtechDevComm.services
		  },
		
		  reloadLater() {
		    let that = this
		    
			that.deviceInput = '';
		    setTimeout(() => {
		    }, 500);
		  },
		
		  onUnload() {
		   
			this.isLoaded = false
		    if (this.btTimer > 0) {
		      this.freeBluetooth();
		    }
		    uni.hideLoading();
		  },
		onPullDownRefresh() {
			// setTimeout(() => {

			// 	// console.log('VUEX数据', this.myDataGlobal);
			// 	// console.log('VUEX数据时间间隔', this.myDataGlobal.myInterval);
			// 	// console.log('实际蓝牙数据', this.myData);
			// 	// console.log('实际蓝牙输入框数据', this.sendData);
			// 	uni.showToast({
			// 		title: '参数更新成功'
			// 	});
			// 	uni.stopPullDownRefresh();
			// }, 1000);
		}, //注册网络状态
		computed: {
			//获取可使用窗口高度
			windowHeight() {

				return uni.getSystemInfoSync().windowHeight + 'px'
			},
			cWidth() {
				return uni.upx2px(this.width);
			},
			cHeight() {
				return uni.upx2px(this.height);
			},
			...mapGetters(['myDataGlobal', 'netWorkType'])
		},
		watch: {
			'myDataGlobal': {
				deep: true,
				immediate: true,
				handler() {
					//监听vuex数据变化，一旦变化及时取数据
					this.myData = this.myDataGlobal;
					//获取的第一个数据就是时间间隔，后两个数据就是获取的数量（目前是不能超过99组，到时候可以考虑设置时间间隔，分开发送这两个数据）
					this.sendData = ((Number(this.myData.myInterval)) * 10).toString() + this.myData.myNumber
				}
			}
		},
		mounted() {
		},
		methods: {
			// 类型选择
			  bindPickerChange(e) {
			    // this.setData({
			    //   //+： 为了确保是个数字类型
			    //   typeIndex: +e.detail.value,
			    // })
				this.typeIndex = +e.detail.value
			  },
			  /**
			   * 输入
			   */
			  deviceInput: function (e) {
			    let value = e.detail.value;
			    // this.setData({
			    //   //剔除【非字母数字】字符，并转大写
			    //   deviceInput: value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase(),
			    // })
				this.deviceInput = value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase()
			  },
			  /**
			   * 读取设备
			   */
			  add: function () {
			    if (this.deviceInput.length != 6) {
			      uni.showToast({
			        icon: 'none',
			        title: '请输入6位序列号',
			      })
			      return
			    }
			    this.openBluetoothAdapter();
			  },
			
			  initDevComm() {
			    // 转换需要发送的数据
			    microtechDevComm.DevComm_Send_CallBack((buffer) => {
			      this.dc_send(buffer);
			    })
			
			    // 转换接收到的数据
			    microtechDevComm.DevComm_Receive_CallBack((buffer) => {
			      this.dc_receive(buffer);
			      // 终止蓝牙通信信号
			      this.terminateDevCommSession();
			      setTimeout(() => {
			        this.freeBluetooth();
			      }, 1500);
			    })
			
			    // 超时cb
			    microtechDevComm.DevComm_Timeout_CallBack(() => {
			      this.dc_timeout();
			    })
			  },
			
			  freeDevComm() {
			    // 重置DevComm实例
			    microtechDevComm.DevComm_Terminate();
			  },
			
			  setBluetoothTimeout(title, ms) {
			    let that = this
			    let btTimer = setTimeout(() => {
			      uni.hideLoading()
			      uni.showModal({
			        title: '提示',
			        content: title,
			        showCancel: false
			      })
			
			      that.freeBluetooth();
			    }, ms);
				that.btTimer = btTimer
			    // that.setData({
			    //   btTimer: btTimer,
			    // })
			  },
			
			  clearBluetoothTimeout() {
			    if (this.btTimer > 0) {
			      clearTimeout(this.btTimer);
			      // this.setData({
			      //   btTimer: 0,
			      // })
				  this.btTimer = 0;
			    }
			  },
			
			
			
			  /**
			   * 打开蓝牙
			   */
			  openBluetoothAdapter() {
			    let that = this
			    uni.openBluetoothAdapter({
			      complete: (res) => {
			        that.onBluetoothAdapterStateChange();
			      },
			      success: (res) => {
			        uni.showLoading({
			          title: '搜索中',
			          mask: true,
			        })
			        // that.setData({
			        //   btAvailable:true,
			        // }) 
					that.btAvailable = true
			        that.startBluetoothDevicesDiscovery()
			        that.setBluetoothTimeout('蓝牙连接超时', 15000)
			      },
			      fail: (res) => {
			        uni.showToast({
			          title: '请打开蓝牙',
			          icon: 'none',
			          duration: 1000,
			          mask: true
			        })
			      }
			    })
			  },
			
			  /**
			   * 关闭蓝牙
			   */
			  closeBluetoothAdapter() {
			    console.log('closeBluetoothAdapter')
			    uni.closeBluetoothAdapter()
			  },
			
			  /**
			   * 监控蓝牙状态
			   */
			  onBluetoothAdapterStateChange() {
			    uni.onBluetoothAdapterStateChange((res) => {
			      console.log('bluetooth:' + 'available:' + res.available + 'discovering:' + res.discovering)
			    })
			  },
			
			  /**
			   * 开始扫描
			   */
			  startBluetoothDevicesDiscovery() {
			    let that = this
			    uni.showLoading({
			      title: '搜索中',
			      mask: true
			    })
				console.log('搜索设备***：',this.deviceService)
			    uni.startBluetoothDevicesDiscovery({
			      allowDuplicatesKey: true,
			      services: this.deviceService,
			      success: (res) => {
					  console.log('搜索设备success：onBluetoothDeviceFound')
			        that.onBluetoothDeviceFound();
			      },
			      fail: (res) => {
			        that.bleConnectProcedureFail()
			      }
			    })
			  },
			
			  /**
			   * 停止扫描
			   */
			  stopBluetoothDevicesDiscovery() {
			    uni.stopBluetoothDevicesDiscovery()
			  },
			
			  /**
			   * 找到设备
			   */
			  onBluetoothDeviceFound() {
			    let that = this
			    uni.onBluetoothDeviceFound((res) => {
			      let device = res.devices[0];
				  
			      console.log('onBluetoothDeviceFound: ' + device.localName);
			      if (!device.localName) {
			        return;
			      }
			
			      let array = device.localName.split('-', 2);
			      if (array.length < 2) {
			        return;
			      }
			      let prefix = device.localName.split('-', 2)[0].trim();
			      let serialNumber = device.localName.split('-', 2)[1].trim();
			
			      let allowedPrefix = that.data.prefix;
			
			      // 匹配设备
			      if (allowedPrefix.indexOf(prefix) >= 0 && serialNumber === that.data.deviceInput) {
			        if (!that.deviceId) {
			          // that.setData({
			          //   deviceId: device.deviceId,
			          // })
					  that.deviceId = device.deviceId
			          that.stopBluetoothDevicesDiscovery()
			          this.createBLEConnection();
			        }
			      }
			    })
			  },
			
			  /**
			   * 建立连接
			   */
			  createBLEConnection() {
			    let that = this
			    uni.showLoading({
			      title: '连接中',
			      mask: true
			    })
			    uni.createBLEConnection({
			      deviceId: that.deviceId,
			      fail: (res) => {
			        console.log('createBLEConnection fail: deviceid' + that.data.deviceI)
			        console.log(res)
			        that.bleConnectProcedureFail()
			      },
			      success: (res) => {
			        that.stopBluetoothDevicesDiscovery()
			        that.getBLEDeviceServices()
			      },
			      timeout: 15000,
			    })
			  },
			
			  /**
			   * 断开连接
			   */
			  closeBLEConnection() {
			    console.log('closeBLEConnection')
			    let that = this
			    if (that.deviceId != '') {
			      uni.closeBLEConnection({
			        deviceId: that.deviceId
			      })
			      that.deviceId = ''
			      that.serviceId = ''
			      that.characteristicId = ''
			    }
			  },
			
			  /**
			   * 获取服务
			   */
			  getBLEDeviceServices() {
			    let that = this
			    uni.getBLEDeviceServices({
			      deviceId: that.data.deviceId,
			      success: (res) => {
			        console.log('getBLEDeviceServices success: ' + res.services.length);
			        for (let i = 0; i < res.services.length; i++) {
			          let service = res.services[i]
			          if (service.uuid === that.data.deviceUuid) {
			            that.data.serviceId = service.uuid;
			            that.getBLEDeviceCharacteristics()
			            break;
			          }
			        }
			      },
			      fail(res) {
			        console.error('getBLEDeviceCharacteristics', res)
			        that.bleConnectProcedureFail()
			      }
			    })
			  },
			
			  /**
			   * 获取特征
			   */
			  getBLEDeviceCharacteristics() {
			    let that = this
			    uni.getBLEDeviceCharacteristics({
			      deviceId: that.data.deviceId,
			      serviceId: that.data.serviceId,
			      success: (res) => {
			        console.log('getBLEDeviceCharacteristics success: ' + res.characteristics.length)
			        for (let i = 0; i < res.characteristics.length; i++) {
			          let characteristic = res.characteristics[i]
			          that.characteristicId = characteristic.uuid;
			          that.notifyBLECharacteristicValueChange()
			        }
			      },
			      fail(res) {
			        console.error('getBLEDeviceCharacteristics', res)
			        that.bleConnectProcedureFail()
			      }
			    })
			  },
			
			  /**
			   * 开启通知
			   */
			  notifyBLECharacteristicValueChange() {
			    let that = this
			    uni.notifyBLECharacteristicValueChange({
			      deviceId: that.deviceId,
			      serviceId: that.serviceId,
			      characteristicId: that.characteristicId,
			      state: true,
			      complete: (res) => {
			        console.log('notifyBLECharacteristicValueChange success');
			        if (!that.btAvailable) {
			          return;
			        }
			
			        that.onBLECharacteristicValueChange()
			        that.bleConnectProcedureComplete()
			        uni.showLoading({
			          title: '正在读取',
			          mask: true
			        })
			        console.log('clearBluetoothTimeout ' + that.data.btTimer);
			        that.clearBluetoothTimeout();
			        console.log('clearBluetoothTimeout ' + that.data.btTimer);
			        that.setBluetoothTimeout('蓝牙传输超时', 10000)
			      },
			    })
			  },
			
			  onBLECharacteristicValueChange() {
			    let that = this
			    uni.onBLECharacteristicValueChange((characteristic) => {
			      console.log('Bluetooth:R: ' + microtechDevComm.hexStringFromArrayBuffer(characteristic.value));
			      microtechDevComm.DevComm_Receive(characteristic.value);
			    })
			  },
			
			  bleConnectProcedureFail() {
			    this.clearBluetoothTimeout();
			    uni.hideLoading();
			    if (!this.data.isLoaded) {
			      return;
			    }
			    uni.showModal({
			      title: '提示',
			      content: '蓝牙连接失败',
			      showCancel: false
			    })
			  },
			
			  bleConnectProcedureComplete() {
			    // 向蓝牙设备发送数据
			    this.initDevComm();
			    microtechDevComm.DevComm_Clear_State();
			    this.getRecordWithIndex(0);
			  },
			
			  /**
			   * 获取对应index索引的数据
			   * @param {number} index 
			   * index = 0 获取最新数据
			   */
			  getRecordWithIndex(index) {
			    let r = microtechDevComm.getRecordWithIndex(1);
			    console.log('DevComm_Send: index: ' + index + ' retrurn: ' + r);
			  },
			
			  // 结束蓝牙通信
			  terminateDevCommSession() {
			    let r = microtechDevComm.terminateDevCommSession();
			    console.log('DevComm_Send: terminate: ' + ' retrurn: ' + r);
			    microtechDevComm.DevComm_Clear_State();
			  },
			
			  freeBluetooth() {
			    console.log('freeBluetooth: ');
			
			    // this.setData({
			    //   btAvailable:false,
			    // })
				this.btAvailable = false
			
			    this.clearBluetoothTimeout();
			    this.freeDevComm();
			    uni.offBLECharacteristicValueChange();
			    uni.offBLEConnectionStateChange();
			    uni.offBluetoothDeviceFound();
			    uni.offBluetoothAdapterStateChange();
			
			    this.closeBLEConnection();
			    this.closeBluetoothAdapter();
			
			  },
			
			  dc_send(buffer) {
			    let that = this
			    uni.writeBLECharacteristicValue({
			      deviceId: that.deviceId,
			      serviceId: that.serviceId,
			      characteristicId: that.characteristicId,
			      value: buffer,
			      complete: (res) => {},
			      fail: (res) => {
			        console.log('writeBLECharacteristicValue fail')
			        console.log(res);
			        that.clearBluetoothTimeout();
			        that.freeBluetooth();
			
			      },
			      success: (res) => {
			        console.log('writeBLECharacteristicValue success')
			      },
			    })
			  },
			
			  dc_receive(buffer) {
			    let result = microtechDevComm.getReslultOfRecord(buffer)
			    console.log('value===>', result);
			    setTimeout(() => {
			      uni.hideLoading()
			    }, 1500);
			  },
			
			  dc_timeout() {
			    uni.hideLoading();
			    uni.showModal({
			      title: '通信异常',
			      content: '设备超时无应答',
			      confirmText: '我知道了',
			      showCancel: false
			    })
			    this.freeBluetooth();
			  },
		}
	};
</script>

<style lang="scss">
	@import "./index.scss";
</style>
